package at.fhj.itm10.ticketmaster.services.datasource;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

/**
 * Datasource locator.
 * 
 * @author Wolfgang Gaar
 */
public class DataSourceLocator {

	private Logger logger = Logger.getLogger(DataSourceLocator.class);
	
	@Resource(name = "TicketmasterJDBC", type = DataSource.class)
	private DataSource dataSource;

	/**
	 * Gets the datasource.
	 * 
	 * @throws NamingException
	 * @see <a href="http://tomee.apache.org/configuring-datasources.html">http://tomee.apache.org/configuring-datasources.html</html>
	 */
	public DataSourceLocator() {
		logger.debug("constructor");
	}

	private void retrieve() throws NamingException {
		if (dataSource == null) {
			logger.warn("dataSource was null, field-based injection failed");
			
			Context ctx = new InitialContext();
			dataSource = (DataSource) ctx
					.lookup("java:comp/env/TicketmasterJDBC");
		}
		
		// Should not happen
		if (dataSource == null) {
			logger.warn("dataSource is null after context lookup");
			throw new NullPointerException("dataSource is null");
		}
		
		logger.info("gathered dataSource = " + dataSource);
	}
	
	public DataSource getDataSource() throws NamingException {
		retrieve();

		return dataSource;
	}

}
